<template>
    <customNavigationBar backUrl="/pages/user/user" :title="isBindding ? '修改银行卡信息' : '绑定银行卡'" />

    <view class="page">
        <view class="item">
            <view class="itemTitle">银行名称</view>

            <view class="inputBox2">
                <input type="text" v-model.trim="form.bankName" placeholder="请输入银行名称" />

                <view class="listBox" v-if="bankList.length != 0">
                    <scroll-view scroll-y="true" style="min-height: 200rpx; max-height: 400rpx">
                        <view class="suggestionsItem" @click="chooseBank(item)" v-for="item in bankList" :key="item.title">
                            {{ item.bankName }}
                        </view>
                    </scroll-view>
                </view>
            </view>
        </view>

        <view class="tips">填写银行全称(例如“中国工商银行”,无需填写支行名),在弹出的选择框中选择对应的银行</view>

        <view class="item">
            <view class="itemTitle">{{ userRole == 4 ? '开户公司名称' : '持卡人名称' }}</view>
            <input type="text" v-model.trim="form.bankCardName" placeholder="请输入账户名称" />
        </view>

        <view class="item">
            <view class="itemTitle">银行卡号</view>
            <input type="text" v-model.trim="form.bankCardNo" placeholder="请输入卡号" />
        </view>
        <view class="item">
            <view class="itemTitle">银行对应手机号</view>
            <input type="tel" :maxlength="11" v-model.trim="form.bankCardPhone" placeholder="请输入银行对应手机号" />
        </view>

        <view class="item" v-if="userRole == 4">
            <view class="itemTitle">银行开户行城市</view>
            <view class="inputBox" @click="openAreaSelect">
                <view class="text" v-if="areaSelectList.length === 0">
                    <span class="placeholder">请选择</span>
                </view>
                <view class="text" v-else>
                    <span v-for="(item, index) in areaSelectList" :key="index">
                        {{ item.areaName === '请选择' ? '' : item.areaName }}
                    </span>
                </view>
                <image class="more" src="/static/common/icon_more.png"></image>
            </view>
        </view>

        <view class="submitButton active" @click="SubmitEvent">确定</view>
    </view>

    <uni-popup ref="popup" type="bottom" border-radius="10px 10px 0 0">
        <view class="popupContent">
            <view class="popupTop">
                <view class="title">
                    <view v-for="(item, index) in areaSelectList" :class="areaCurrentIndex == index && 'active'" @click="chooseItem(index)">{{ item?.areaName }}</view>
                </view>
                <image src="/static/common/icon_close.png" class="close" @click="closePopup"></image>
            </view>

            <view class="scrollViewBox">
                <view class="title">请选择</view>

                <scroll-view scroll-y="true" class="scrollView">
                    <view class="scrollContent">
                        <view
                            class="item"
                            :class="item?.areaNo === areaSelectList[areaCurrentIndex]?.areaNo && 'active'"
                            v-for="(item, index) in allAreaList"
                            :key="index"
                            @click="selectArea(index)"
                        >
                            {{ item?.areaName }}
                        </view>
                    </view>
                </scroll-view>
            </view>
        </view>
    </uni-popup>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch, nextTick } from 'vue';
import { checkStrLengthIsNotZero as checkStr, debounceImmediate } from '@/utils/utils';
import { onShow } from '@dcloudio/uni-app';
import { commonApis, getUserInfoMethod, userApis } from '@/utils/apis';

onShow(() => {
    getBinddingList();
    getUserInfo();
});

let userRole = ref(null);
const getUserInfo = async () => {
    await getUserInfoMethod();
    userRole.value = JSON.parse(uni.getStorageSync('userInfomation')).identityType;
};
let isBindding = ref(false);
const getBinddingList = async () => {
    let res = await userApis.getBankDetail();
    isBindding.value = !!res.data.bankCardNumber;
};
let form = reactive({
    bankName: '',
    bankCardName: '',
    bankCardNo: '',
    bankCardPhone: '',
    bankProvCode: '',
    bankAreaCode: '',
    bankCode: ''
});

const searchFlage = ref(false);
watch(
    () => form.bankName,
    (newVal, oldVal) => {
        if (searchFlage.value) {
            searchFlage.value = false;
            return;
        }
        getBankList();
    }
);

const bankList = ref([]);
const getBankList = debounceImmediate(async () => {
    userApis.getBankList({ bankName: form.bankName }).then((res) => {
        bankList.value = res.data;
    });
}, 300);

const chooseBank = (item) => {
    form.bankName = item.bankName;
    form.bankCode = item.bankCode;
    bankList.value = [];
    searchFlage.value = true;
};

const SubmitEvent = async () => {
    if (!form.bankName) {
        uni.showToast({
            icon: 'none',
            title: '请填写银行名称',
            mask: true,
            duration: 2000
        });

        return;
    }
    if (!form.bankCardName) {
        uni.showToast({
            icon: 'none',
            title: userRole.value == 4 ? '请填写开户公司名称' : '请填写持卡人名称',
            mask: true,
            duration: 2000
        });
        return;
    }

    if (!form.bankCardNo) {
        uni.showToast({
            icon: 'none',
            title: '请填写银行卡号',
            mask: true,
            duration: 2000
        });
        return;
    }

    if (!form.bankCardPhone) {
        uni.showToast({
            icon: 'none',
            title: '请填写银行对应手机号',
            mask: true,
            duration: 2000
        });
        return;
    }

    if (!form.bankCode) {
        uni.showModal({
            title: '提示',
            content: '填写的银行名称格式错误。请重新输入银行全称（例如“中国工商银行”,无需填写支行名）,在弹出的选择框中选择对应的银行。 ',
            showCancel: false,
            success(res) {
                if (res.confirm) {
                    form.bankName = '';
                }
            }
        });
        return;
    }

    if (userRole.value == 4) {
        if (!form.bankProvCode || !form.bankAreaCode) {
            uni.showToast({
                icon: 'none',
                title: '请选择银行开户城市',
                mask: true,
                duration: 2000
            });
            return;
        }

        userApis.updateCompanyBankInfomation(form).then(() => {
            uni.showToast({
                icon: 'none',
                title: '提交成功',
                mask: true,
                duration: 2000
            });

            setTimeout(() => {
                uni.navigateBack();
            }, 2000);
        });
        return;
    }

    // form
    userApis
        .updateBankDetail({
            bankUsername: form.bankCardName,
            bankCardNumber: form.bankCardNo,
            bankName: form.bankName,
            bankCardPhone: form.bankCardPhone,
            bankCode: form.bankCode
        })
        .then(() => {
            uni.showToast({
                icon: 'none',
                title: '提交成功',
                mask: true,
                duration: 2000
            });

            setTimeout(() => {
                uni.navigateBack();
            }, 2000);
        });
};

let areaCurrentIndex = ref(0);
let allAreaList = ref([]);
let areaSelectList = reactive([]);

const chooseItem = async (index) => {
    areaCurrentIndex.value = index;
    let res = await commonApis.getArea({
        parentAreaNo: index === 0 ? '' : areaSelectList[index - 1].areaNo,
        parentLevel: index === 0 ? '' : areaSelectList[index - 1].areaLevel
    });
    allAreaList.value = res.data;
};

const selectArea = async (index) => {
    if (areaSelectList.length > areaCurrentIndex.value) {
        areaSelectList.length = areaCurrentIndex.value + 1;
    }
    let selectItem = allAreaList.value[index];
    areaSelectList[areaCurrentIndex.value] = selectItem;

    switch (areaCurrentIndex.value) {
        case 0:
            form.bankProvCode = selectItem.areaNo;
            break;
        case 1:
            form.bankAreaCode = selectItem.areaNo;
            closePopup();
            break;
    }

    if (areaCurrentIndex.value < 1) {
        areaCurrentIndex.value++;
        areaSelectList[areaCurrentIndex.value] = {
            areaName: '请选择'
        };
        let res = await commonApis.getArea({
            parentAreaNo: selectItem.areaNo,
            parentLevel: selectItem.areaLevel
        });
        allAreaList.value = res.data;
    }
};

// 弹出地区选择
const popup = ref();
const openAreaSelect = () => {
    nextTick(async () => {
        popup.value.open();
        areaCurrentIndex.value = 0;
        if (areaSelectList.length == 0) {
            areaSelectList.push({
                areaName: '请选择'
            });
        }

        let res = await commonApis.getArea({});
        allAreaList.value = res.data;
    });
};
const closePopup = () => {
    nextTick(() => {
        popup.value.close();
    });
};
</script>

<style lang="scss" scoped>
.page {
    padding: 90rpx 24rpx 0;
}

.tips {
    margin-top: -36rpx;
    margin-bottom: 30rpx;
    font-size: 18rpx;
    color: #999;
}

.item {
    width: 100%;
    margin-bottom: 40rpx;
    padding-bottom: 24rpx;
    display: flex;
    align-items: center;
    border-bottom: 2rpx solid #f2f3f5;
    gap: 40rpx;
    .itemTitle {
        width: 190rpx;
        font-size: 26rpx;
        color: #333333;
    }

    input {
        flex: 1;
        font-size: 26rpx;
        color: #333333;
        text-align: left;
        &::placeholder {
            color: #999;
        }
    }
    .inputBox2 {
        position: relative;
        flex: 1;
        input {
            width: 100%;
        }
    }
}

.submitButton {
    width: 100%;
    height: 80rpx;
    background: #999999;
    border-radius: 40rpx;
    font-size: 28rpx;
    color: #fff;
    line-height: 80rpx;
    text-align: center;
    margin: 0 auto;
    margin-top: 90rpx;
    &.active {
        background: #2c72ff;
        color: #fff;
    }
}

.listBox {
    position: absolute;
    z-index: 5;
    width: 100%;
    top: 100%;
    left: 0;
    background-color: #fff;
    padding: 20rpx 30rpx;
    box-shadow: 0 0 5rpx 5rpx rgba(0, 0, 0, 0.08);

    .suggestionsItem {
        height: 60rpx;
        border-bottom: 2rpx solid #ccc;
        font-size: 24rpx;
        line-height: 60rpx;
        color: #393939;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;

        &:last-child {
            border-bottom: none;
        }
    }
}
.inputBox {
    flex: 1;
    display: flex;
    align-items: center;
    position: relative;

    .text {
        flex: 1;
        font-size: 28rpx;
        color: #333333;

        .placeholder {
            color: #808080;
        }
    }
    .more {
        margin-left: 20rpx;
        width: 24rpx;
        height: 24rpx;
    }

    input {
        flex: 1;
        height: 40rpx;
        font-size: 24rpx;
        color: #393939;
        line-height: 40rpx;

        &::placeholder {
            color: #999999;
        }
    }

    .listBox {
        position: absolute;
        z-index: 5;
        width: 100%;
        top: 100%;
        left: 0;
        background-color: #fff;
        padding: 20rpx 30rpx;
        box-shadow: 0 0 5rpx 5rpx rgba(0, 0, 0, 0.08);

        .suggestionsItem {
            height: 60rpx;
            border-bottom: 2rpx solid #ccc;
            font-size: 24rpx;
            line-height: 60rpx;
            color: #393939;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;

            &:last-child {
                border-bottom: none;
            }
        }
    }
}
.popupContent {
    width: 100%;
    background: #ffffff;
    border-radius: 24rpx 24rpx 0rpx 0rpx;
    padding: 46rpx 24rpx calc(env(safe-area-inset-bottom) + 20rpx);

    .popupTop {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .title {
            font-size: 32rpx;
            color: #333333;
            display: flex;
            align-items: center;
            gap: 10rpx;
            view {
                border-radius: 8rpx;
                display: block;
                padding: 0 10rpx;
                max-width: 160rpx;
                height: 48rpx;
                font-size: 26rpx;
                color: #333333;
                line-height: 48rpx;
                text-align: center;
                background: #f2f3f5;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;

                &.active {
                    background: #2c72ff;
                    color: #fff;
                }
            }
        }
        .close {
            width: 40rpx;
            height: 40rpx;
        }
    }

    .scrollViewBox {
        padding: 20rpx 0 0;
        .title {
            font-size: 32rpx;
            color: #333333;
            margin-bottom: 30rpx;
        }

        .scrollView {
            height: 40vh;
            width: 100%;

            .scrollContent {
                .item {
                    font-size: 32rpx;
                    color: #333333;
                    padding: 18rpx 24rpx;
                    border-radius: 24rpx;
                    &:last-child {
                        margin: 0;
                    }

                    &.active {
                        color: #2c72ff;
                        background: #f2f2f2;
                    }
                }
            }
        }
    }
}
</style>
